package org.lcc.Controller;

import com.github.pagehelper.PageInfo;
import org.lcc.Service.QuestionService;
import org.lcc.model.VO.QuestionAllVo;
import org.lcc.model.VO.SearchSet;
import org.lcc.model.entity.Question;
import org.lcc.util.ApiResponseMe;
import org.lcc.util.ExcelQuestionExtractor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping
@Tag(name = "试题管理", description = "试题相关的接口")
public class QuestionController {
    @Autowired
    private QuestionService questionService;
    //excle批量导入试题信息
    @Operation(summary = "批量导入试题", description = "通过Excel文件批量导入试题")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "导入成功"),
        @ApiResponse(responseCode = "400", description = "文件为空或解析失败")
    })
    @PostMapping("/importQuestionExcel")
    public ApiResponseMe uploadQuestionFile(
            @Parameter(description = "Excel文件", required = true)
            @RequestParam("excelFile") MultipartFile file,
            @Parameter(description = "创建者ID", required = true)
            @RequestPart("creatorId") String creatorId,
            @Parameter(description = "题库名称", required = true)
            @RequestPart("questionName") String questionName) {
        boolean result = false;
        if (file.isEmpty()) {
            return new ApiResponseMe(400, "文件为空", null);
        }
        try (InputStream inputStream = file.getInputStream()) {
            List<Question> questions = ExcelQuestionExtractor.extractQuestionsFromExcel(inputStream);
            for (Question question : questions) {
                question.setCreatorId(creatorId);
                question.setQuestionName(questionName);
                System.out.println("创建人: " + question.getCreatorId());
                System.out.println("所属题库: " + question.getQuestionName());
                System.out.println("试题类型: " + question.getType());
                System.out.println("试题内容: " + question.getContent());
                System.out.println("选项: " + question.getOptions());
                System.out.println("答案: " + question.getAnswer());
                System.out.println("章节: " + question.getSubject());
                System.out.println("难度: " + question.getDifficulty());
                System.out.println("解析: " + question.getAnalysis());
                System.out.println("-------------------------");
            }
            result = questionService.batchInsertion(questions);
            return ApiResponseMe.shape(result, "批量导入试题成功");
        } catch (IOException e) {
            e.printStackTrace();
            return ApiResponseMe.shape(result, "文件解析失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponseMe.shape(result, "文件解析失败");
        }
    }
    //单题导入
    @Operation(summary = "单题导入", description = "导入单个试题")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "导入成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @PostMapping("/importQuestion")
    public ApiResponseMe importQuestion(
            @Parameter(description = "试题信息", required = true)
            @RequestBody Question question) {
        //验证数据有效性
        if (question == null){
            return ApiResponseMe.error(400,"数据无效");
        }
        Boolean qu =questionService.importQuestion(question);
        if (qu){
            return ApiResponseMe.shape(qu,"试题导入成功");
        }
        return ApiResponseMe.shape(qu,"试题导入失败");
    }
    //题库所属的试题
    @Operation(summary = "获取题库试题", description = "获取指定题库中的所有试题，支持分页和筛选")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "未选择题库")
    })
    @GetMapping("/nerv/selectQuestion")
    public ApiResponseMe selectQuestionAll(
            @Parameter(description = "题库名称", required = true)
            @RequestParam("question_name") String question_name,
            @Parameter(description = "题型", required = false)
            @RequestParam(value = "type", defaultValue = "") String type,
            @Parameter(description = "难度", required = false)
            @RequestParam(value = "difficulty", defaultValue = "") String difficulty,
            @Parameter(description = "章节", required = false)
            @RequestParam(value = "subject", defaultValue = "") String subject,
            @Parameter(description = "关键词", required = false)
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            @Parameter(description = "页码", required = false)
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页数量", required = false)
            @RequestParam(value = "size", defaultValue = "10") Integer size) {
        if (question_name == null) {
            return ApiResponseMe.error(400, "未选择题库");
        }

        // 使用 PageHelper 获取分页数据
        PageInfo<QuestionAllVo> pageInfo = questionService.selectQuestionAll(question_name, type, difficulty, subject, keyword, page, size);

        if (pageInfo != null && pageInfo.getList() != null) {
            Map<String, Object> result = new HashMap<>();
            result.put("records", pageInfo.getList());
            result.put("total", pageInfo.getTotal());
            result.put("size", pageInfo.getPageSize());
            result.put("current", pageInfo.getPageNum());
            result.put("pages", pageInfo.getPages());
            return ApiResponseMe.success(result);
        }
        return ApiResponseMe.error(400, "请检查该题库是否有试题加入");
    }

    //题目详情
    @Operation(summary = "获取题目详情", description = "根据题目ID获取题目详细信息")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "未选择记录")
    })
    @GetMapping("/selectQuestion_id")
    public ApiResponseMe selectQuestion(@RequestParam("question_id") Integer question_id){
        if (question_id==null){
            return ApiResponseMe.error(400,"未选择记录");
        }
        Question question =questionService.selectQuestion(question_id);
        if (question!=null){
            return ApiResponseMe.success(question);
        }
        return ApiResponseMe.error(400,"暂未找到该题详情,请联系管理员");
    }
    //修改题目
    @Operation(summary = "修改题目", description = "修改指定题目的信息")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "修改成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @PostMapping("/updateQuestion")
    public ApiResponseMe updateQuestion(@RequestBody Question question){
        //验证数据有效性
        if (question == null){
            return ApiResponseMe.error(400,"数据无效");
        }
        if (question.getQuestionId()==null){
            return ApiResponseMe.error(400,"未选择记录");
        }

        Boolean qu =questionService.updateQuestion(question,question.getQuestionId());
        if (qu){
            return ApiResponseMe.shape(qu,"试题修改成功");
        }
        return ApiResponseMe.shape(qu,"试题修改失败");
    }
    //删除题目
    @Operation(summary = "删除题目", description = "批量删除指定题目")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "400", description = "未选择记录")
    })
    @DeleteMapping("/deleteQuestion")
    public ApiResponseMe deleteQuestion(@RequestParam(value = "question_id") List<Integer> questionIds) {
        if (questionIds == null || questionIds.isEmpty()) {
            return ApiResponseMe.error(400, "未选择记录");
        }
        Boolean qu = questionService.deleteQuestions(questionIds);
        if (qu) {
            return ApiResponseMe.shape(qu, "试题删除成功");
        }
        return ApiResponseMe.shape(qu, "试题删除失败");
    }
    //题目搜素
    @Operation(summary = "搜索题目", description = "根据条件搜索题目")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "搜索成功"),
        @ApiResponse(responseCode = "400", description = "未选择筛选条件")
    })
    @GetMapping("/searchQuestion")
    public ApiResponseMe searchQuestion(@RequestParam("question_name") String question_name, @RequestParam("type") String type, @RequestParam("difficulty") String difficulty){
        if (question_name.equals("")&&type.equals("")&&difficulty.equals("")){
            return ApiResponseMe.error(400,"未选择筛选条件");
        }
        SearchSet questions =questionService.searchQuestion(question_name,type,difficulty);
        if (questions!=null){
            return ApiResponseMe.success(questions);
        }
        return ApiResponseMe.error(400,"暂未找到该题详情,请联系管理员");
    }
}
